#include "threadPool.h"

// ANSI 颜色定义
const char *COLOR_DIR = "\033[1;34m"; // 目录蓝色高亮显示
const char *COLOR_FILE = "\033[1;32m"; // 文件绿色高亮显示
const char *COLOR_RESET = "\033[0m";

int lsFunc(MYSQL *mysql, dirStack_t *dirstack, const char *username, const char *buf, char *ret_buf){
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query[1024] = {0};
    int parent_id = -1;

    if(buf[0] == '\0' || strcmp(buf, ".") == 0){ // 判断路径buf
        // 当前目录
        parent_id = dirstack->top->data;
    } else if(strcmp(buf, "..") == 0){ // 上一级目录，查找parent_id
        snprintf(query, sizeof(query),
                 "SELECT parent_id FROM fileSystem WHERE id = %d AND username = '%s';", dirstack->top->data, username);

        if(mysql_query(mysql, query)){
            sprintf(ret_buf, "Query error (..): %s\n", mysql_error(mysql));
            return -1;
        }

        res = mysql_store_result(mysql);
        if((row = mysql_fetch_row(res)) == NULL || row[0] == NULL){
            mysql_free_result(res);
            sprintf(ret_buf, "Already at root, no parent directory\n");
            return 0;
        }
        parent_id = atoi(row[0]);
        mysql_free_result(res);
    } else {
        // 这里只处理绝对路径
        snprintf(query, sizeof(query),
                 "SELECT id FROM fileSystem WHERE path = '%s' AND username = '%s' LIMIT 1;", buf, username);
        if(mysql_query(mysql,query)){
            sprintf(ret_buf, "Query error (path lookup): %s\n", mysql_error(mysql));
            return -1;
        }

        res = mysql_store_result(mysql);
        if((row = mysql_fetch_row(res)) == NULL){
            sprintf(ret_buf, "Path not found: %s for user %s\n", buf, username);
            mysql_free_result(res);
            return -1;
        }

        parent_id = atoi(row[0]);
        mysql_free_result(res);
    }

    // 查询该目录下所有文件/目录
    snprintf(query, sizeof(query),
             "SELECT filename, type FROM fileSystem WHERE parent_id = %d AND username = '%s' ORDER BY filename;", parent_id, username);

    if(mysql_query(mysql, query)){
        sprintf(ret_buf, "Query error (list contents): %s\n", mysql_error(mysql));
        return -1;
    }

    res = mysql_store_result(mysql);
    ret_buf[0] = '\0'; // 清空结果缓冲区

    while((row = mysql_fetch_row(res)) != NULL){
        const char *filename = row[0];
        const char *type = row[1];

        if(strcmp(type, "d") == 0){
            strcat(ret_buf, COLOR_DIR);
        } else{
            strcat(ret_buf, COLOR_FILE);
        }

        strcat(ret_buf, filename);
        strcat(ret_buf, COLOR_RESET);
        strcat(ret_buf, "\t");
    }

    mysql_free_result(res);
    return 0;
}
